import { Notification } from 'element-ui';
import { ListStore } from '@/store';
import { INITIAL_FORM_QUERY_VALUE, LIST_NAME, LOAD_MANUAL_PRICE_LIST_REQUEST_TASK_NAME } from '@/views/manual-price/constants';
import {
  loadGoodsList,
  loadListCellular,
  queryChannel,
  listCostPriceGoods,
  listLimit,
  loadListStore,
  loadCompeteStoreNames,
  addTimeTasksApi,
} from './api';
import { errorHandler } from '@/utils';
import { export_json_to_excel, formatJson } from '@/utils/vendor/Export2Excel';
import { message } from '@/utils/util';

export default class Store extends ListStore {
  formQueryValue = { ...INITIAL_FORM_QUERY_VALUE };

  querying = false;

  importVisible = false;

  cellularList = [];

  cellularMap = new Map();

  exporting = false;

  resultData = [];

  goodsDetailVisible = false;

  goodsDetail = {};

  competeStoreNames = [];

  // 分时段调价弹窗相关参数
  adjustPriceByRangeModalValue = {
    visible: false,
    okBtnLoading: false,
  };

  // 变更分时段调价弹窗相关参数
  setAdjustPriceByRangeModalValue = params => {
    this.adjustPriceByRangeModalValue = {
      ...this.adjustPriceByRangeModalValue,
      ...params,
    };
  };

  // 加载列表
  loadGoodsList = async ({ loadAction = 'reset', pageSize: inputPageSize, pageNum: inputPageNum } = {}) => {
    const channelCodes = this.formQueryValue.channelCodes;
    if (channelCodes.length === 0) {
      message('提示', '请选择渠道', 'warning');
      return;
    }
    if (channelCodes.length > 10) {
      message('提示', '渠道选择不能超过10个', 'warning');
      return;
    }
    const { topChannelCode, salesRankStart, salesRankEnd, cellularCode, storeLevel, storeType } = this.formQueryValue || {};
    if (!salesRankStart || !salesRankEnd) {
      message('提示', '请选择商品排名', 'warning');
      return;
    }
    if (salesRankStart > salesRankEnd) {
      message('提示', '开始排名大于结束排名', 'warning');
      return;
    }
    if (salesRankEnd - salesRankStart > 200) {
      message('提示', '排名范围不能超过200', 'warning');
      return;
    }
    //渠道名称对应关系
    const channelNameMap = new Map();
    //提取三方店铺名称
    const storeNames = [];
    let resultChannel = await queryChannel(channelCodes, storeLevel, storeType, cellularCode);
    if (!resultChannel || resultChannel.length === 0) {
      message('提示', '没有符合条件的渠道', 'warning');
      this.formQueryValue = { ...this.formQueryValue, cellularForm: null };
      return;
    } else {
      //组装请求参数
      const cellularForm = resultChannel.map(item => {
        return {
          cellularCode: item.cellularCode,
          competeStoreNames: item.competeStoreNames,
          storeNames: [...item.storeNames, ...item.competeStoreNames],
          yfStoreNames: item.channelStoreList.map(item => {
            channelNameMap.set(item.channelName, item.channelCode);
            storeNames.push(item.channelName);
            return item.channelName;
          }),
        };
      });
      this.formQueryValue = { ...this.formQueryValue, cellularForm };
    }
    await this.loadList({
      requestTaskName: LOAD_MANUAL_PRICE_LIST_REQUEST_TASK_NAME,
      listName: LIST_NAME,
      loadAction,
      pageSize: inputPageSize,
      pageNum: inputPageNum,
      loadDataFunc: async ({ pageSize, pageNum }) => {
        let result = await loadGoodsList({
          topChannelCode: topChannelCode,
          goodsCodes: this.formQueryValue.goodsCode ? [this.formQueryValue.goodsCode] : null,
          cellularForm: this.formQueryValue.cellularForm,
          salesRankEnd: salesRankEnd ? salesRankEnd : 200,
          salesRankStart: salesRankStart ? salesRankStart : 1,
        });
        let data = [];
        let total = 0;
        if (result.length === 0) {
          this.resultData = [];
          return { data, total };
        }
        total = result.length;
        //获取店铺信息
        const storeMap = new Map();
        try {
          const stores = await loadListStore(topChannelCode, storeNames);
          if (stores && stores.length > 0) {
            stores.map(storeItem => {
              const key = storeItem.channelName;
              storeMap.set(key, storeItem);
            });
          }
        } catch (e) {
          message('错误', '批量获取门店信息失败', 'error');
        }

        //封装商品请求参数
        const channelGoodsMap = new Map();
        result.forEach(item => {
          const channelCode = channelNameMap.get(item.storeName);
          if (!channelCode) {
            return;
          }
          const goodsCodes = channelGoodsMap.get(channelCode);
          if (!goodsCodes) {
            const codes = [];
            codes.push(item.goodsCode);
            channelGoodsMap.set(channelCode, codes);
          } else {
            goodsCodes.push(item.goodsCode);
            channelGoodsMap.set(channelCode, goodsCodes);
          }
        });
        const postCostPriceArray = [];
        const postLimitArray = [];
        channelGoodsMap.forEach(function(value, key) {
          postCostPriceArray.push(listCostPriceGoods(key, value));
          postLimitArray.push(listLimit(key, value));
        });
        //获取成本价
        let goodsCostPriceList = [];
        try {
          goodsCostPriceList = await Promise.all(postCostPriceArray);
        } catch (e) {
          message('错误', '获取商品成本价，零售价失败', 'error');
        }
        const goodsCostPriceMap = new Map();
        if (goodsCostPriceList && goodsCostPriceList.length > 0) {
          goodsCostPriceList.map(item => {
            item.map(costItem => {
              const key = costItem.channelCode + costItem.goodsCode;
              goodsCostPriceMap.set(key, costItem);
            });
          });
        }
        //获取商品是否限购
        let postLimitList = [];
        try {
          postLimitList = await Promise.all(postLimitArray);
        } catch (e) {
          message('错误', '获取限购规则失败', 'error');
        }
        const goodsLimitMap = new Map();
        if (postLimitList && postLimitList.length > 0) {
          postLimitList.map(item => {
            item.map(limitItem => {
              const key = limitItem.channelCode + limitItem.goodsCode;
              goodsLimitMap.set(key, limitItem);
            });
          });
        }

        result = result.map(item => {
          const channelCode = channelNameMap.get(item.storeName);
          const store = storeMap.get(item.storeName);
          const key = channelCode + item.goodsCode;
          //起送价
          const minPriceTip = store ? store.minPriceTip : '';
          //成本价
          const costPrice = goodsCostPriceMap.get(key)?.costPrice;
          //零售价
          const retailPrice = goodsCostPriceMap.get(key)?.retailPrice;
          //毛利率= （商品原价（渠道价）- 成本价）/ 商品原价
          const profitRate = this.getProfitRate(costPrice, item.channelPrice);
          const goodsLimit = goodsLimitMap.get(key);
          let limit = goodsLimit && (goodsLimit.limitNum > 0 || goodsLimit.activityPriceLimit > 0) ? '是' : '否';
          return {
            ...item,
            cellularName: this.cellularMap.get(item.cellularCode)?.cellularName,
            costPrice: costPrice,
            retailPrice: retailPrice,
            profitRate: profitRate,
            channelCode: channelCode,
            minPrice: minPriceTip,
            limit: limit,
          };
        });
        this.resultData = result;
        //手动分页，开始下标数
        const beginIndex = pageSize * pageNum - pageSize;
        for (let i = 0; i < pageSize; i++) {
          let index = beginIndex + i;
          const item = this.resultData[index];
          if (item) {
            data.push(item);
          }
        }
        return { data, total };
      },
    });
  };

  //计算毛利率
  getProfitRate = (costPrice, channelPrice) => {
    if (!costPrice || !channelPrice) {
      return 0;
    }
    return ((channelPrice - costPrice) / channelPrice).toFixed(2);
  };

  // 查询
  queryGoodsList = value => {
    this.formQueryValue = value;
    this.loadGoodsList({ loadAction: 'pageNumChange', pageNum: 1 });
  };

  // 当前页变更
  pageNumChange = page => {
    const pageSize = page.pageSize;
    const pageNum = page.pageNum;
    this.paging(pageSize, pageNum);
  };

  // 每页条数变更
  pageSizeChange = page => {
    const pageNum = page.pageNum;
    const pageSize = page.pageSize;
    this.paging(pageSize, pageNum);
  };
  paging = (pageSize, pageNum) => {
    //手动分页，开始下标数
    const data = [];
    const beginIndex = pageSize * pageNum - pageSize;
    for (let i = 0; i < pageSize; i++) {
      let index = beginIndex + i;
      const item = this.resultData[index];
      if (item) {
        data.push(item);
      }
    }
    this.list[LIST_NAME].data = data;
    this.list[LIST_NAME] = { ...this.list[LIST_NAME], data, pageSize, pageNum };
  };

  //关闭导入对话框
  onCloseImportModal = () => {
    this.importVisible = false;
  };
  //打开导入对话框
  onOpenImportModal = value => {
    this.importVisible = true;
    if (value) {
      this.storeFormValue = value;
    }
  };
  //导出商品价格
  exportGoodsPrice = async () => {
    try {
      this.exporting = true;
      const list = this.resultData;
      const tHeader = [
        '商品名称',
        '成本价',
        '零售价',
        '毛利率',
        '起送价',
        '商品原价',
        '商品特价',
        '销售排名',
        '月售',
        '竞对原价最低价',
        '竞对特价最低价',
        '调原价',
        '调特价',
        '竞对最高销量',
        '蜂窝总销量',
        '限购规则',
        '限购频率',
        '限购数量',
        '特价限购',
        '商品编码',
        '渠道编码',
        '所属蜂窝',
      ];
      const filterVal = [
        'goodsName',
        'costPrice',
        'channelPrice',
        'profitRate',
        'minPrice',
        'originPrice',
        'activityPrice',
        'salesRank',
        'monthSaled',
        'competeOriginPrice',
        'competeActivityPrice',
        'newChannelPrice',
        'newActivityPrice',
        'competeMaxSales',
        'cellularSales',
        'limit',
        'limitFrequency',
        'limitNum',
        'activityPriceLimit',
        'goodsCode',
        'channelCode',
        'cellularCode',
      ];
      const data = formatJson(filterVal, list);
      export_json_to_excel(tHeader, data, '商品价格信息');
      this.exporting = false;
    } catch (e) {
      this.exporting = false;
      message('提示', '导出列表异常', 'error');
    }
  };

  listCellular = async () => {
    try {
      this.cellularList = await loadListCellular();
      if (this.cellularList.length > 0) {
        this.cellularList.forEach(item => {
          this.cellularMap.set(item.cellularCode, item);
        });
      }
    } catch (e) {
      message('提示', '获取蜂窝列表异常', 'error');
    }
  };

  //关闭商品详情弹窗
  onCloseGoodsDetailModal = () => {
    this.goodsDetail = {};
    this.goodsDetailVisible = false;
  };

  listCompeteStoreNames = async cellularCode => {
    try {
      this.competeStoreNames = await loadCompeteStoreNames(cellularCode);
    } catch (e) {
      message('错误', '获取竞对门店失败', 'error');
    }
  };

  //打开商品详情弹窗
  onOpenGoodsDetailModal = async row => {
    await this.listCompeteStoreNames(row.cellularCode);
    this.goodsDetail = row;
    this.goodsDetailVisible = true;
  };

  // 初始加载数据
  init = async () => {
    await this.listCellular();
  };

  /**
   * 点击分时段调价按钮
   */
  onAdjustPriceByRange = () => {
    this.setAdjustPriceByRangeModalValue({ visible: true });
  };

  // AdjustPriceByRangeModal 点击确定
  onAdjustPriceByRangeModalOK = async ({ topChannelCode, timeTasks }) => {
    this.setAdjustPriceByRangeModalValue({ okBtnLoading: true });
    try {
      await addTimeTasksApi({ topChannelCode, timeTasks });
      Notification({ tip: '提示', message: '分时段调价任务导入成功', type: 'success' });
      this.setAdjustPriceByRangeModalValue({ okBtnLoading: false, visible: false });
    } catch (error) {
      errorHandler({ error });
      this.setAdjustPriceByRangeModalValue({ okBtnLoading: false });
    }
  };

  // AdjustPriceByRangeModal 点击确定
  onAdjustPriceByRangeModalClose = () => {
    this.setAdjustPriceByRangeModalValue({ visible: false });
  };
}
